<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="isShowDialog = true">添加角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="list">
        <!-- 放置列 -->
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template v-slot="{ row }">
            <el-input v-if="row.isInput" v-model="row.cacheData.name" size="mini" type="text" />  <!-- isInput为true显示输入框 -->
            <span v-else>{{ row.name }}</span> <!-- isInput为true显示名称 -->
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="200" label="启用">
          <template v-slot="{ row }">
            <el-switch v-if="row.isInput" v-model="row.cacheData.state" :active-value="1" :inactive-value="0" />
            <span v-else>{{ row.state === 1 ? '启用' : row.state === 0 ? '未启用' : '未知状态' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template v-slot="{ row }">
            <el-input v-if="row.isInput" v-model="row.cacheData.description" size="mini" type="textarea" />
            <span v-else> {{ row.description }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="" align="center" label="操作">
          <template v-slot="{ row }">
            <template v-if="row.isInput">
              <el-button size="mini" type="primary" @click="confirmEdit(row)">确认</el-button>
              <el-button size="mini" @click="row.isInput = false">取消</el-button>
            </template>
            <template v-else>
              <el-button size="mini" type="text" @click="openPermissionAssignment(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" style="margin-right:10px" @click="showInput(row)">编辑</el-button>
              <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="confirm(row.id)">
                <el-button slot="reference" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <!-- 放置分页组件 -->
        <el-pagination
          layout="prev, pager, next"
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          :total="pageParams.total"
          @current-change="changePage"
        />
      </el-row>
    </div>
    <!-- 新增角色弹出框 -->
    <el-dialog width="500px" title="新增角色" :visible.sync="isShowDialog" @close="close">
      <el-form ref="ruleForm" label-width="120px" :model="ruleForm" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="ruleForm.name" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item label="启用" prop="state">
          <!-- :active-value="1" :inactive-value="0"  1是开启开关，2是关闭开关 -->
          <el-switch v-model="ruleForm.state" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="ruleForm.description" type="textarea" :rows="3" size="mini" style="width:300px" />
        </el-form-item>
        <!--  按钮 -->
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="addBtn">确认</el-button>
              <el-button size="mini" @click="close">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分配权限弹窗 -->
    <el-dialog title="权限分配" :visible.sync="showPermissionDialog">
      <el-tree
        ref="perTree"
        node-key="id"
        :data="perList"
        :props="{label:'name'}"
        :show-checkbox="true"
        :default-checked-keys="permIds"
        :check-strictly="true"
      />
      <el-row type="flex" justify="center">
        <el-col>
          <div style="text-align: center">
            <el-button type="primary" @click="changeRolePermission">确认</el-button>
            <el-button @click="checkBoxClose">取消</el-button>
          </div>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleList, addRole, amendRole, deleteRole, particularsRole, changeRolePermission } from '@/api/role'
import { getPermission } from '@/api/permission'
import { transListToTreeData } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      currentID: null, // 点击后ID
      permIds: [], // 获取选中元素选中的 ID
      perList: [], // 权限列表数据
      showPermissionDialog: false, // 分配权限弹窗
      isShowDialog: false, // 添加角色弹窗
      list: [],
      pageParams: {
        page: 1,
        pagesize: 5,
        total: 0
      },
      ruleForm: {
        name: '',
        description: '',
        state: 0 // 默认为 1 启用
      },
      rules: {
        name: [
          { required: true, message: '数据不能为空', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '数据不能为空', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const res = await getRoleList(this.pageParams) // 获取角色信息请求
      this.list = res.data.data.rows // 角色列表获取
      this.list.forEach(ele => {
        // 添加的动态属性，没有响应式的特点
        // this.$set(目标对象，属性名称，初始值)
        this.$set(ele, 'isInput', false)
        this.$set(ele, 'cacheData', { // 新建一个缓存对象，储存一份list数据
          name: ele.name,
          description: ele.description,
          state: ele.state
        })
      })
      this.pageParams.total = res.data.data.total // 赋值总页数
    },
    changePage(Page) {
      this.pageParams.page = Page // 修改页面的数据
      this.getRoleList() // 渲染
    },
    addBtn() { // 点击确认发起请求新增角色
      this.$refs.ruleForm.validate(async isOK => {
        if (isOK) {
          const res = await addRole(this.ruleForm)
          this.$message.success(res.data.message) // 新增角色成功弹框提示
          this.close() // 调用函数清除表单数据，并且关闭表单
          this.getRoleList() // 重新渲染
        }
      })
    },
    close() { // 清除表单数据，并且关闭表单
      this.$refs.ruleForm.resetFields()
      this.isShowDialog = false
    },
    showInput(row) { // 编辑按钮的开关，点击编辑按钮显示输入框
      row.isInput = true
      // 下面三行代码表示点击编辑后修改内容，点击取消后还是可以回退到编辑前的状态
      row.cacheData.name = row.name
      row.cacheData.state = row.state
      row.cacheData.description = row.description
    },
    async confirmEdit(row) { // 编辑角色
      if (row.cacheData.description && row.cacheData.name) {
        await amendRole({ ...row.cacheData, id: row.id })
        await this.getRoleList()
        Object.assign(row.isInput, { state: row.state, name: row.name, description: row.description })
        Object.assign(row, { isInput: false })
        this.$message.success('更新角色成功')
      } else {
        this.$message.error('数据不能为空')
      }
    },
    async confirm(id) {
      await deleteRole(id)
      this.$message.success('删除角色成功')
      if (this.list.length === 1) this.pageParams.page-- // 删除的数据是本页面左后一条，往前前进一页
      this.getRoleList() // 重新渲染
    },
    async  openPermissionAssignment(id) { // 分配权限按钮，点击显示弹框
      const res = await getPermission() // 获取权限点列表
      this.perList = transListToTreeData(res.data.data, 0)
      const data = await particularsRole(id) // 获取角色详情
      this.permIds = data.data.data.permIds // 获取选中的ID
      this.currentID = id // 存储点击后的ID
      this.showPermissionDialog = true
    },
    checkBoxClose() { // 清除复选框勾选，并且关闭弹窗
      this.showPermissionDialog = false
      this.permIds = []
    },
    async changeRolePermission() { // 确认修改后的权限分配
      await changeRolePermission({ id: this.currentID, permIds: this.$refs.perTree.getCheckedKeys() }) // 修改角色权限
      this.$message.success('分配权限成功')
      this.checkBoxClose()
    }
  }

}
</script>

<style scoped>
.role-operate {
  padding: 10px;
}
</style>
